package main

import (
	"os"
	"runtime"
	"log"
	"flag"
)

var (
	keep = flag.Bool("keep_generated_files", false, "Do not delete the generated files after we are done with them.")
	use5 = flag.Bool("5", false, "proxy 5c")
	use6 = flag.Bool("6", false, "proxy 6c")
	use8 = flag.Bool("8", false, "proxy 8c")
	//the below are just passed through to the compiler
	out = flag.String("o", "", "specify output file*")
	inc = flag.String("I", "", "search for packages in DIR*")
	dec = flag.Bool("d", false, "print declarations*")
	frm = flag.Bool("f", false, "print stack frame structure*")
	pnc = flag.Bool("h", false, "panic on an error*")
	ass = flag.Bool("S", false, "print the assembly language*")
	ver = flag.Bool("V", false, "print the compiler version*")
	uns = flag.Bool("u", false, "disable package unsafe*")
	ptr = flag.Bool("w", false, "print the parse tree after typing*")
	lex = flag.Bool("x", false, "print lex tokens*")
)

func parse_args() (save bool, argv, files []string, err os.Error) {
	flag.Usage = func() {
		log.Println("Usage:", os.Args[0], "infile+")
		flag.PrintDefaults()
		log.Println("* passed directly to proxied compiler")
	}
	flag.Parse()

	save = !*keep

	files = flag.Args()

	//determine compiler to proxy
	comp := ""
	switch {
	case *use5:
		comp = "5"
	case *use6:
		comp = "6"
	case *use8:
		comp = "8"
	default:
		//none requested, use default compiler for current arch
		switch runtime.GOARCH {
		case "arm":
			comp = "5"
		case "amd64":
			comp = "6"
		case "386":
			comp = "8"
		}
	}
	if comp == "" {
		err = os.NewError("Cannot determine compiler to proxy")
		return
	}

	//build argv
	add := func(s ...string) {
		argv = append(argv, s...)
	}
	flg := func(i *bool, s string) {
		if *i {
			add("-" + s)
		}
	}

	add(comp + "g")

	if *out != "" {
		add("-o", *out)
	}
	if *inc != "" {
		add("-I", *inc)
	}
	flg(dec, "d")
	flg(frm, "f")
	flg(pnc, "h")
	flg(ass, "S")
	flg(ver, "V")
	flg(uns, "u")
	flg(ptr, "w")
	flg(lex, "x")

	return
}
